package com.damozan.iossupersign.controller;

import java.util.List;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.damozan.iossupersign.base.ApiResult;
import com.damozan.iossupersign.cache.RedisCache;
import com.damozan.iossupersign.cache.RedisKey;
import com.damozan.iossupersign.enums.ServiceError;
import com.damozan.iossupersign.exception.ServiceException;
import com.damozan.iossupersign.model.bo.AuthorizeBO;
import com.damozan.iossupersign.model.dto.AppleResultDTO;
import com.damozan.iossupersign.model.po.AppleAccountPO;
import com.damozan.iossupersign.service.appleaccount.AppleAccountBSService;
import com.damozan.iossupersign.service.appleaccount.AppleAccountService;
import com.damozan.iossupersign.service.device.DeviceBSService;
import com.damozan.iossupersign.thridparty.appleapi.AppleApiService;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Peter.Hong
 * @date 2019/12/10
 */
@Controller
@RequestMapping("appleAccount")
@Slf4j
public class AppleAccountController {

    private static final Integer DEFAULT_PAGE = 1;

    private final AppleAccountBSService appleAccountBSService;


    private final AppleApiService appleApiService;

    private final AppleAccountService appleAccountService;

    private final DeviceBSService deviceBSService;
    
    private final RedisCache redisCache;

    
    public AppleAccountController( AppleAccountService appleAccountService,AppleApiService appleApiService,AppleAccountBSService appleAccountBSService,DeviceBSService deviceBSService,RedisCache redisCache) {
        this.appleAccountBSService = appleAccountBSService;
        this.deviceBSService = deviceBSService;
        this.appleApiService = appleApiService;
        this.appleAccountService = appleAccountService;
        this.redisCache = redisCache;
        
    }

    @RequestMapping("/index")
    public String index(Model model){
        return search(DEFAULT_PAGE,null, model);
    }

    @PostMapping("addAccount")
    @ResponseBody
    public ApiResult<String> addAppleAccount(AppleAccountPO appleAccountPO){
        ApiResult<String> result = new ApiResult<>();
        //確認蘋果帳號是否存在
        try{
            if(appleAccountBSService.getAccountByAccount(appleAccountPO)==null){
                appleAccountBSService.addAppleAccount(appleAccountPO);
                result.setCode(ApiResult.SUCCESS_CODE);
                result.setMsg(ApiResult.SUCCESS_MSG);
                log.info("add Apple Account Success");
            }else{
                result.setMsg("账号已存在");
            }
        }catch (ServiceException se){
            result.setMsg(se.getErrorMsg());
        }catch (Exception e){
            log.error("",e);
            result.setMsg(ServiceError.SERVER_ERROR.msg);
        }
        return result;
    }

    @GetMapping("/search")
    @ApiOperation(value = "搜尋")
    public String search(@RequestParam(value = "page") Integer currentPage,
                         AppleAccountPO appleAccountPO ,
                                Model model) {
        Page<AppleAccountPO>  appleAccountPOS = appleAccountBSService.selectAppleAccountByCondition(currentPage,appleAccountPO);
        model.addAttribute("page", appleAccountPOS);
        model.addAttribute("accounts", appleAccountPOS.getRecords());
        return "supersignature/appleaccount/index";
    }

    
    @GetMapping("/getDeviceList")
    @ApiOperation(value = "获取设备")
    @ResponseBody
    public  ApiResult<String> getDeviceList(@RequestParam(value = "id") Long id,  Model model) {
    	 ApiResult<String> result = new ApiResult<>();
    	  
    	 AppleAccountPO appleAccountPO = appleAccountBSService.getAccountById(id);
    	  
         AuthorizeBO authorizeBO = AuthorizeBO.builder()
                 .iss(appleAccountPO.getIssuerId())
                 .kid(appleAccountPO.getKid())
                 .p8(appleAccountPO.getP8())
                 .csr(appleAccountPO.getCsr()).build();
         //取得機器下的設備
         List<AppleResultDTO> appleDeviceDataList = appleApiService.getNumberOfAvailableDevices(authorizeBO);
         
         //同步帳號下的機器資訊
         deviceBSService.insertList(appleDeviceDataList,appleAccountPO.getId());
         Long deviceNumber = new Long(appleDeviceDataList.size());
         addAppleDeviceCountToRedis(appleAccountPO.getAccount(),deviceNumber);
         
         List<AppleResultDTO> certificates = appleApiService.selectCertificates(authorizeBO);
         AppleResultDTO cerData = null;
         if(CollectionUtils.isEmpty(certificates)){
             //創建新證書
             cerData = appleApiService.insertCertificates(authorizeBO);
         }else{
             cerData = certificates.stream().findFirst().get();
         }
         
         log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
         
         
         log.info("certificates:"+certificates);
         
         log.info("cerData:"+cerData);
         
         log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    	 return result;
    }
    
    public Long addAppleDeviceCountToRedis(String appleAccount, Long deviceCount){
        return redisCache.hincr(RedisKey.APPLE_ACCOUNT_DEVICE_COUNT_KEY,appleAccount,Intenger.);
    }

    @ApiOperation(value = "/uploadP12", notes = "上传p12", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    @PostMapping(value = "/uploadP12")
    public ApiResult<String> uploadPackage(@RequestPart(value = "p12")MultipartFile file, @RequestParam("account")String account) {
        ApiResult<String> result = new ApiResult<>();
        try {

            appleAccountBSService.uploadP12(file, account);

            result.setCode(ApiResult.SUCCESS_CODE);
            result.setMsg(ApiResult.SUCCESS_MSG);

        }catch (ServiceException e){
            result.setMsg(e.getErrorMsg());
        }
        return result;
    }

}